<template>
  <div>
    <el-form>
      <el-form-item label="SPU名称">
        <el-input
          placeholder="请你输入SPU名称"
          v-model="spuParams.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择"  v-model="spuParams.tmId">
          <el-option
            :label="trademark.tmName"
            :value="trademark.id"
            v-for="(trademark, index) in allTradeMarkArr"
            :key="trademark.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" v-model="spuParams.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          :file-list="imgListArr"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="unSaleAttrIdAndName"
          :placeholder="
            unSaleAttrIdAndName.length > 0
              ? `您还有${unSaleAttrIdAndName.length}未选择`
              : `没得选啦`
          "
        >
          <!-- 添加属性值 -->
          <el-option
            :label="sale.name"
            :value="`${sale.id}:${sale.name}`"
            v-for="(sale, index) in unSelectSaleAttr"
            :key="sale.id"
          ></el-option>
        </el-select>
        <el-button
          style="margin-left: 10px"
          type="primary"
          size="default"
          :icon="Plus"
          @click="addSaleAttr"
          :disabled="!unSaleAttrIdAndName"
          >添加销售属性值</el-button
        >
        <el-table
          border
          stripe
          style="margin: 10px 0px"
          :data="spuHasSaleAttrArr"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="属性名"
            width="120"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值名称列表">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 0px 5px"
                v-for="(saleValue, index) in row.spuSaleAttrValueList"
                :key="saleValue.id"
                class="mx-1"
                closable
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                :type="saleValue.id % 2 == 0 ? 'success' : 'warning'"
              >
                {{ saleValue.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.flag"
                placeholder="请输入属性值"
                size="small"
                clearable
                @blur="toLook(row)"
                style="width: 100px"
                v-model="row.inputValue"
              ></el-input>
              <el-button
                v-else
                type="primary"
                :icon="Plus"
                size="default"
                @click="addAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="default"
                @click="spuHasSaleAttrArr.splice($index, 1)"
                :icon="Delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" size="default" @click="save">保存</el-button>
        <el-button size="default" @click="cancel"
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
//引入组合式API
import { ref, computed } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";

import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";

//引入接口
import {
  reqAllaTradeMark,
  reqAllAttr,
  reqImageList,
  reqHaveSale,
  reqSaveAndUpdateInfo, //添加SPU或者修改已有的SPU
} from "@/api/product/spu/spu";

//控制对话框显示与隐藏
const dialogVisible = ref(false);
//定义将来添加spu和修改spu需要带给服务器的参数
let spuParams = ref({});
//已有spu下的全部的品牌数据
let allTradeMarkArr = ref([]);

let allSaleAttrArr = ref([]);
let imgListArr = ref([]);

let spuHasSaleAttrArr = ref([]);

//照片墙相关的代码
//存储预览图片地址
const dialogImageUrl = ref("");
//手机SPU还未选择销售属性ID与名字
let unSaleAttrIdAndName = ref("");
//删除图片回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles);
};
//预览回调
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//图片上传成功的回调
const handleSuccess = (response, uploadFile, uploadFiles) => {
  //前两个参数:图片上传成功的信息
  //最后的参数:图片上传成功以后，照片墙全部图片数据
  imgListArr.value = uploadFiles;
};

//父组件给子组件的的回调
let initHasSpuData = async (spu) => {
  spuParams.value = spu;
  //获取全部品牌数据
  let ps1 = reqAllaTradeMark();
  //获取照片墙的数据
  let ps2 = reqImageList(spu.id);
  //获取已有的销售属性
  let ps3 = reqAllAttr();
  //spu已有的销售属性
  let ps4 = reqHaveSale(spu.id);
  let result = await Promise.all([ps1, ps2, ps3, ps4]);
  imgListArr.value = result[1].map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });

  allTradeMarkArr.value = result[0];
  allSaleAttrArr.value = result[2];
  spuHasSaleAttrArr.value = result[3];
};

//计算出当前SPU,还没有选择销售属性
let unSelectSaleAttr = computed(() => {
  let result = allSaleAttrArr.value.filter((item) => {
    return spuHasSaleAttrArr.value.every((item1) => {
      return item.name != item1.saleAttrName;
    });
  });

  return result;
});
//添加销售属性的回调
let addSaleAttr = () => {
  //整理参数
  //新增的销售属性ID与名字
  const [baseSaleAttrId, saleAttrName] = unSaleAttrIdAndName.value.split(":");
  //服务器需要销售属性对象
  let newSaleATTR = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] };
  spuHasSaleAttrArr.value.push(newSaleATTR);
  //清空下拉框数据
  unSaleAttrIdAndName.value = "";
};
//添加属性值的回调
let addAttr = (row) => {
  row.flag = true;
  //初始值为空方便后面做判断
  row.inputValue = "";
};
//失去焦点的回调
let toLook = (row) => {
  //做输入框的判断，不能为空
  if (row.inputValue.trim() == "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    return;
  }
  //收集属性值不能和前面的属性值重复
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === row.inputValue;
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值名称不能重复",
    });
    //清空数据
    row.inputValue = "";
    //切换到按钮
    row.flag = false;
    return;
  }

  //切换到按钮
  row.flag = false;
  //整理新的属性值数据
  let newSaleAttr = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputValue,
  };
  //像原有的属性值对象添加新属性值
  row.spuSaleAttrValueList.push(newSaleAttr);
  //清空数据
  row.inputValue = "";
};
//保存按钮的回调
const save = async () => {
  //整理照片墙参数
  spuParams.value.spuImageList = imgListArr.value.map((item) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  //销售属性名称
  spuParams.value.spuSaleAttrValueList = spuHasSaleAttrArr.value;
  //发请求
  try {
    let result = await reqSaveAndUpdateInfo(spuParams.value);
    ElMessage({
      type: "success",
      message: "修改成功",
    });
    //触发自定义事件
    emit("changeScene", {
      scences: 0,
      flag: spuParams.value.id ? "update" : "add",
    });
  } catch (error) {
    ElMessage({
      type: "error",
      message: "修改失败",
    });
  }
  //清空数据
  reMoveAttr();
};
//点击SPU 的时候，当前自组件发请求
const initAddSpu = async (c3Id: string | number) => {
  //添加spu三级id
  spuParams.value.category3Id = c3Id;
  //获取全部品牌数据
  let ps1 = reqAllaTradeMark();
  //spu已有的销售属性
  let ps3 = reqAllAttr();
  let result = await Promise.all([ps1, ps3]);
  allTradeMarkArr.value = result[0];
  allSaleAttrArr.value = result[1];
};


//取消
const cancel=()=>{
  emit('changeScene', {
    scences:0,
    flag:spuParams.value.id ? "update" : "add",
  })
  reMoveAttr()
}
//清空数据回调
const reMoveAttr = () => {
  (spuParams.value = ""), (imgListArr.value = ""), (spuParams.value = "");
};
//自定义触发事件
let emit = defineEmits(["changeScene"]);
defineExpose({ initHasSpuData, initAddSpu });
</script>

<style scoped>
</style>



